﻿module Sustainalytics.Portfolio {
    import Common = Sustainalytics.Common;

    


    export class SystemPortfolioController {



        public selectedGroups: any[]=[];
        public allGroups: any[]=[];
        private accountId: string;
        private userId: string;
        private portfolioStatus: boolean; //true for changed(updated), false for not changed
        private portfolioFilter: PortfolioFilterDto;
        private searchData: any = { "name": "", "type": PortfolioTypes.System, "status": PortfolioSharingStatus.Private };

        public constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private portfolio:PortfolioDto,
            private SystemPortfolioService: ISystemPortfolioService,
            private staticObjects: Common.IStaticObjects,
            private notificationFactory: Common.INotificationFactory,
            private $modal: Common.IModal,
            private $modalInstance: Common.IModalInstance
        ) {
            
            var ctx = this;

            if (ctx.$rootScope["userInfo"] == null) {
                ctx.$rootScope["userInfo"] = angular.fromJson(localStorage.getItem("sust_userInfo"));
            }
            ctx.accountId = ctx.$rootScope["userInfo"].accountId;
            ctx.userId = ctx.$rootScope["userInfo"].userId;

            $scope["systemPortfolio"] = ctx;
            ctx.portfolio = portfolio;
            ctx.portfolioFilter = new PortfolioFilterDto();
            ctx.portfolioFilter.sharingStatus = PortfolioSharingStatus.Private;
            ctx.portfolioFilter.isMyPortfolio = true;
            ctx.portfolioFilter.portfolioType = PortfolioTypes.System;
            ctx.loadInfo();
            
        }



        loadInfo() {
            var ctx = this;
            ctx.$rootScope['loading'] = true;
          
            var getRelatedGroupsPromise: ng.IPromise<Sustainalytics.Portfolio.ManualSystemPortfolioDto>;
            var promiseAll: ng.IPromise<any[]>;

            var getAllGroupsPromise: ng.IPromise<Sustainalytics.Portfolio.RelatedUniverses[]> = ctx.SystemPortfolioService.getAllAutomaticSystemPortfolios(ctx.userId, ctx.accountId);
            
         
            if (ctx.isInEditMode()) {
                getRelatedGroupsPromise = ctx.SystemPortfolioService.getRelatedSystemPortfolios(ctx.portfolio.id, ctx.userId, ctx.accountId);

             
                promiseAll = ctx.$q.all([getAllGroupsPromise, getRelatedGroupsPromise]);
                promiseAll.then(data => {
                        this.allGroups = data[0];
                        this.selectedGroups = data[1].relatedUniverses;
                        ctx.allGroups.forEach(item => {
                            ctx.selectedGroups.forEach(selected => {
                                if (item.id == selected.id) {
                                    item.selected = true;
                                }
                            });
                        });

                    })
                .finally(() => {
                    this.$rootScope['loading'] = false;
                });
            }
            else
            {
                promiseAll = ctx.$q.all([getAllGroupsPromise]);
                promiseAll.then(data => {
                        this.allGroups = data[0];
                        this.selectedGroups = new Array();
                    })
                .finally(() => {
                    this.$rootScope['loading'] = false;
                });
            }

            promiseAll
                .catch((err) => {   
                    if (err) {
                        ctx.notificationFactory.error('', ctx.staticObjects.getErrorMesageByStatusCode(err));
                    }
                    ctx.notificationFactory.error('', ctx.staticObjects.getErrorMesageByStatusCode());
                    }
                )
                .finally(() => {
                    this.$rootScope['loading'] = false;
                });
        }

        isInEditMode(): boolean {
            var ctx = this;
            return !(ctx.portfolio==undefined || ctx.portfolio.id == undefined);
        }


        private saveSystemPortfolio() {
            this.$rootScope['loading'] = true;
            var savePromise: ng.IPromise<any> = this.SystemPortfolioService.savePortfolio(this.portfolio, this.selectedGroups);

            savePromise.then(() => {
                this.$rootScope["loading"] = false;
                this.portfolioStatus = true;
                this.$modalInstance.close({ portfolioStatus: this.portfolioStatus });
            });
        }


        savePortfolio() {


            var tempFilter: PortfolioFilterDto = new PortfolioFilterDto();
            tempFilter.portfolioType = PortfolioTypes.All;
            tempFilter.namePortfolio = this.portfolio.name;
            tempFilter.sharingStatus = PortfolioSharingStatus.All;

            var promiseCount: ng.IPromise<PortfolioListDto> = this.SystemPortfolioService.getPortfolioCount(tempFilter, this.accountId, this.userId);

            promiseCount.then(result => {

                var portfolioCountTemp = result['count'];
                var portfolioTemp = result.portfolios[0];
                if (portfolioCountTemp === 0) {
                  this.saveSystemPortfolio();
                } else {
                    if (portfolioCountTemp >= 1) {
                        if ((!portfolioTemp.isSystemPortfolio) || (portfolioTemp.isReadonly))
                        {
                            this.notificationFactory.error("", "A portfolio with this name already exists!");
                            var element = document.getElementById("portfolioAddSearchInput");
                            if (element)
                                element.focus();
                        }
                        else
                        {
                            var modalInstancePortfolio = this.$modal.open({
                                templateUrl: 'Views/Portfolio/portfolioExists_dialog.tpl.html',
                                controller: 'PortfolioCheckController',
                                size: 'lg',
                                backdrop: 'static',
                                resolve: {
                                    message() {
                                        return "Are you sure you want to overwrite the existing Portfolio?";
                                    },
                                    informationMessage() {
                                    }
                                }
                            });

                            modalInstancePortfolio.result.then((out) => {
                                if (out['portfolioCheck'] === true) {
                                    this.$rootScope['loading'] = true;
                                    this.portfolio.id = portfolioTemp.id;
                                    this.saveSystemPortfolio();
                                }
                                else {
                                    $("#portfolioAddSearchInput").focus();
                                }
                            });
                        }
                    }
                }

            });

        }

        cancel() {
            var ctx = this;
            ctx.portfolioStatus = false;
            ctx.$modalInstance.close({"portfolioStatus": ctx.portfolioStatus });
        }

        public selectPortfolioAdd(item) {
            var ctx = this;
            ctx.portfolioFilter.namePortfolio = item.name;
            ctx.portfolioFilter.portfolioId = item.id;
            //ctx.$rootScope['screeningExportDetails'].SelectedPortfolio = item.name;
        }
    }
    angular.module(portfolioModuleName).controller("SystemPortfolioController",
        ["$rootScope", "$scope", "$q", "$location","portfolio", "SystemPortfolioService", 
            "staticObjects", "notificationFactory", '$modal',"$modalInstance",
            SystemPortfolioController]);
} 